package com.beaven.imclient.presenter.group;

import android.text.TextUtils;
import com.beaven.imclient.R;
import com.beaven.model.Factory;
import com.beaven.model.data.DataSource;
import com.beaven.model.data.helper.GroupHelper;
import com.beaven.model.model.api.RspModel;
import com.beaven.model.model.api.group.GroupCreateModel;
import com.beaven.model.model.card.GroupCard;
import rx.Subscriber;
import rx.subscriptions.CompositeSubscription;

/**
 * author: Beaven
 * time: 2017/5/26 9:47
 */

public class GroupPresenter implements GroupContract.Presenter, DataSource.FailedCallBack {

  private GroupContract.View view;
  private CompositeSubscription subscription;

  public GroupPresenter(GroupContract.View view) {
    this.view = view;
    subscription = new CompositeSubscription();
  }

  @Override public void subscribe() {

  }

  @Override public void unSubscribe() {
    view.hideLoading();
    subscription.clear();
  }

  @Override public void createGroup() {
    String groupName = view.getGroupName();
    if (TextUtils.isEmpty(groupName)) {
      view.showText(R.string.data_null);
      return;
    }
    view.showLoading();
    subscription.add(GroupHelper.createGroup(new GroupCreateModel(groupName))
        .subscribe(new Subscriber<RspModel<GroupCard>>() {
          @Override public void onCompleted() {

          }

          @Override public void onError(Throwable e) {
            view.showText(R.string.data_network_error);
            view.hideLoading();
          }

          @Override public void onNext(RspModel<GroupCard> groupCardRspModel) {
            if (groupCardRspModel.isSuccess()) {
              view.showText(R.string.add_success);
              view.start();
            } else {
              Factory.decodeRspCode(groupCardRspModel, GroupPresenter.this);
            }
            view.hideLoading();
          }
        }));
  }

  @Override public void loadDataFail(int strRes) {
    view.showText(strRes);
  }
}
